package com.opdar.platform.core.view;

import com.opdar.platform.core.base.ViewTemplate;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.ClassUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by shiju on 2017/1/19.
 */
public class FreemarkerViewTemplate implements ViewTemplate {
    Configuration configuration;
    private String prefix = "";
    private String suffix = ".ftl";

    public FreemarkerViewTemplate() {
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    public void setSuffix(String suffix) {
        this.suffix = suffix;
    }

    @Override
    public void render(String s, ServletRequest servletRequest, ServletResponse servletResponse) {
        if(configuration == null){
            //init
            configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
            if(prefix.startsWith("classpath:")){
                String[] paths = prefix.split(":");
                configuration.setClassLoaderForTemplateLoading(Thread.currentThread().getContextClassLoader(),paths[1]);
            }else{
                ServletContext servletContext = ((HttpServletRequest) servletRequest).getSession().getServletContext();
                configuration.setServletContextForTemplateLoading(servletContext,prefix);
            }
            configuration.setDefaultEncoding("UTF-8");
        }

        Map<String, Object> root = new HashMap<String, Object>();
        Enumeration<String> attributeNames = servletRequest.getAttributeNames();
        while (attributeNames.hasMoreElements()){
            String key = attributeNames.nextElement();
            root.put(key,servletRequest.getAttribute(key));
        }
        try{
            // 获取模板
            Template t = configuration.getTemplate(s.concat(suffix));
            // 准备输出， 使用模板的编码作为本页的charset
            servletResponse.setContentType("text/html; charset=" + t.getEncoding());
            PrintWriter out = servletResponse.getWriter();
            t.process(root, out);
        }catch(Exception e){
            throw new RuntimeException("Template Error : ", e);
        }
    }
}
